package com.serializeQueue.impl;


import com.serializeQueue.SerializableTask;
import com.serializeQueue.TaskRemoveFailedException;
import com.serializeQueue.TaskSerializer;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
    将任务序列化在文件系统中的序列化器
 */
public class FileTaskSerializer implements TaskSerializer {

    private File container;

    public FileTaskSerializer(String dir) {
        this(new File(dir));
    }

    public FileTaskSerializer(File container) {
        if (container.exists()) {
            if (container.isDirectory()) {
                this.container = container;
            } else {
                throw new RuntimeException("必须是一个目录:" + container.getAbsolutePath());
            }

        } else {
            if (!container.mkdirs()) {
                throw new RuntimeException("创建失败:" + container.getAbsolutePath());
            }
        }
    }

    @Override
    public void serialize(SerializableTask serializableTask) throws Exception {

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(container, serializableTask.getId())));

        //将对象序列化在本地
        objectOutputStream.writeObject(serializableTask);

        //关流
        objectOutputStream.close();

    }

    @Override
    public void remove(String id) throws TaskRemoveFailedException {
        if (!new File(container, id).delete()) {
            throw new TaskRemoveFailedException();
        }
    }

    private SerializableTask file2Task(File file) {

        try {

            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));

            Object object = objectInputStream.readObject();

            objectInputStream.close();

            return (SerializableTask) object;

        } catch (Exception ignore) {
            return null;
        }


    }

    @Override
    public List<SerializableTask> allTasks() {

        List<SerializableTask> rs = new ArrayList<>();

        File[] files = container.listFiles();

        if (files != null) {
            for (File file : files) {
                SerializableTask serializableTask = file2Task(file);

                if (serializableTask != null) {
                    rs.add(serializableTask);
                }

            }
        }

        return rs;
    }

}
